import path from 'path'
import consts from './consts'

const { ASSET_PATH, ASSET_PREFIX } = consts

const utils = {
  isProd(app) {
    if (app) {
      return app.get('env') === 'production'
    }
    return process.env.NODE_ENV !== 'production'
  },
  pathJoin(...dirs) {
    return path.join(__dirname, '..', ...dirs)
  },
  getAssetFile(file = '') {
    return utils.pathJoin('..', consts.ASSET_DIR, file)
  },
  getAssetPath(req) {
    return function assetPath(assetUrl) {
      const idx = assetUrl.lastIndexOf('/') || 0
      const filePath = assetUrl.substring(0, idx)
      const assetFile = assetUrl.substring(idx + 1)
      const [name, suffix] = assetFile.split('.')

      let url = ''
      if (utils.isProd(req.app)) {
        const manifest = req.app.get('assetsManifest')

        url += ASSET_PREFIX
        if (name in manifest) {
          url += `${consts.BASE_PATH}/${manifest[name][suffix]}`
        } else {
          url += `${ASSET_PATH}/${filePath}/${name}.${suffix}`
        }
      } else {
        url += `${ASSET_PATH}/${filePath}/${name}.${suffix}`
      }
      return url
    }
  },
}

export default utils
